/*
 * Copyright 2013 David Schreiber
 *           2013 John Paul Nalog
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.funny.learning.english.activity;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.funny.learning.english.BaseActivity;
import com.funny.learning.english.R;
import com.funny.learning.english.adapter.GameAdapter;
import com.funny.learning.english.adapter.LearnedCourseAdapter;
import com.funny.learning.english.adapter.SubTopicAdapter;
import com.funny.learning.english.adapter.TopicAdapter;
import com.funny.learning.english.api.BaseAjaxCallBack.IAjaxCallbackMMK;
import com.funny.learning.english.api.Define;
import com.funny.learning.english.api.TiengAnhApi;
import com.funny.learning.english.cover_flow.FancyCoverFlow;
import com.funny.learning.english.dialog.ShowPopup;
import com.funny.learning.english.model.CourseEntity.Level;
import com.funny.learning.english.model.GameTypeEntity;
import com.funny.learning.english.model.SubTopicEntity;
import com.funny.learning.english.model.TopicEntity;
import com.funny.learning.english.model.UserEntity;
import com.funny.learning.english.util.PreferenceShUtil;

public class HomeActivity extends BaseActivity implements
		OnItemSelectedListener, OnClickListener {
	
	private final String GAME_NGHE = "nghe";
	private final String GAME_NOI_TU = "noi-tu";
	private final String GAME_CHON_TU = "chon-tu";
	private final String GAME_TU_VUNG = "tu-vung";
	private final String GAME_VIET_TU = "viet-tu";
	private final String GAME_CHON_ANH = "chon-anh";
	
	protected String slugGameName;

	protected String slugSubTopicName;

	protected String slugTopicName;
	
	private String TAG = "HomeActivity";

	// =============================================================================
	// Child views
	// =============================================================================
	private ShowPopup showPopupAccount;
	private ShowPopup showPopupSetting;
	
	private PopupWindow popupWindowAcc;
	private PopupWindow popWindowSetting;
	
	private LayoutInflater inflater;
	
	private FancyCoverFlow fancyCoverFlowTopic;
	private FancyCoverFlow fancyCoverFlowSubTopic;
	private FancyCoverFlow fancyCoverFlowGame;

	private int pos;

	private TopicAdapter adapter1;
	private SubTopicAdapter adapter2;
	private GameAdapter adapter3;
	
	private ArrayList<TopicEntity> arrTopic;
	private ArrayList<SubTopicEntity> arrSubTopic;
	private ArrayList<GameTypeEntity> arrGameType;
	

	private Button btPlay;

	private String accPref = "";

	private UserEntity userEntity;
	private ImageView ivAcc;
	private ImageView ivMenu;
	
	private String slugTopic = "";
	private String slugSubTopic = "";
	private String slugGame = "";
	private String thumbGame = "";
	
	private DrawerLayout drawerLayout;
	private ImageView ivIcon;
	private ListView lvLearned;
	private Button btHistory;
	private Button btLogout;
	private TextView tvName;
	private TextView tvCoin;
	private TextView tvReLean7day;
	private TextView tvReLean28ay;
	private TextView tvMyCourse;
	private TextView tvPhuongPhapHoc;
	private TextView tvHelp;
	private TextView tvAppHot;
	private TextView tvLogout;

	// =============================================================================
	// Supertype overrides
	// =============================================================================

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		File fileMDir = new File(this.getFilesDir(), "m");
		File fileIDir = new File(this.getFilesDir(), "i");
		if(!fileMDir.exists()){
			fileMDir.mkdir();
		}
		if(!fileIDir.exists()){
			fileIDir.mkdir();
		}
//		if(!appication.isLogin()){
//			Intent intent = new Intent(HomeActivity.this,
//					WellcomeActivity.class);
//			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
//					| Intent.FLAG_ACTIVITY_NEW_TASK);
//			startActivity(intent);
//		}
		
//		checkLogin();
		initUI();
//		addData();
		initData();
		
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		switch (arg1.getId()) {
		case R.id.fancyCoverFlow:
			adapter1.setPos(arg2);
			break;
		case R.id.fancyCoverFlow1:
			adapter2.setPos(arg2);
			break;
		case R.id.fancyCoverFlow2:
			adapter3.setPos(arg2);
			break;

		default:
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	// =============================================================================
	// Private classes
	// =============================================================================

	
	private void initUI(){
		inflater = LayoutInflater.from(activity);
		drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
		ivIcon = (ImageView)findViewById(R.id.ivIcon);
		
		ivAcc = (ImageView)findViewById(R.id.ivAcc);
		ivMenu = (ImageView)findViewById(R.id.ivMenu);
		
		ivAcc.setOnClickListener(this);
		ivMenu.setOnClickListener(this);
		
		initSlide();
		
		this.fancyCoverFlowTopic = (FancyCoverFlow) this
				.findViewById(R.id.fancyCoverFlow);
		this.fancyCoverFlowSubTopic = (FancyCoverFlow) this
				.findViewById(R.id.fancyCoverFlow1);
		this.fancyCoverFlowGame = (FancyCoverFlow) this
				.findViewById(R.id.fancyCoverFlow2);
		btPlay = (Button) this.findViewById(R.id.btPlay);
		btPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Log.d(TAG, "slugGame:" + slugGame + ":slug Topic:" + slugSubTopic);
				if (slugGame.equals(GAME_CHON_TU)) {
					Intent intent = new Intent(HomeActivity.this,
							ChonTuActivity.class);
					initIntent(intent);
					startActivity(intent);
				} else if (slugGame.equals(GAME_NOI_TU)) {
					Intent intent1 = new Intent(HomeActivity.this,
							KhopTuActivity.class);
					initIntent(intent1);
					startActivity(intent1);
				} else if (slugGame.equals(GAME_NGHE)) {
					Intent intent1 = new Intent(HomeActivity.this,
							LangNgheActivity.class);
					initIntent(intent1);
					startActivity(intent1);
				} else if (slugGame.equals(GAME_VIET_TU)) {
					Intent intent1 = new Intent(HomeActivity.this,
							LangNgheVaVietActivity.class);
					initIntent(intent1);
					startActivity(intent1);
				} else if (slugGame.equals(GAME_CHON_ANH)) {
					Intent intent1 = new Intent(HomeActivity.this,
							TimHinhAnhActivity.class);
					initIntent(intent1);
					startActivity(intent1);
				} else if (slugGame.equals(GAME_TU_VUNG)) {
					Intent intent1 = new Intent(HomeActivity.this,
							TuVungActivity.class);
					initIntent(intent1);
					startActivity(intent1);
				}
			}
		});
		
		ivIcon.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(drawerLayout.isActivated()){
					drawerLayout.closeDrawer(ivIcon);
				}else{
					drawerLayout.openDrawer(Gravity.START);
				}
			}
		});
	}
	
	private void initSlide() {
		tvReLean7day = (TextView)findViewById(R.id.tvReLean7day);
		tvReLean28ay = (TextView)findViewById(R.id.tvReLean28ay);
		tvMyCourse = (TextView)findViewById(R.id.tvMyCourse);
		tvPhuongPhapHoc = (TextView)findViewById(R.id.tvPhuongPhapHoc);
		tvHelp = (TextView)findViewById(R.id.tvHelp);
		tvAppHot = (TextView)findViewById(R.id.tvAppHot);
		tvLogout = (TextView)findViewById(R.id.tvLogout);
		
		tvMyCourse.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(HomeActivity.this, CourseLearnedActivity.class);
				startActivity(intent);
			}
		});
		tvAppHot.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(HomeActivity.this, AppHotActivity.class);
				startActivity(intent);
			}
		});
		
	}

	private void checkLogin(){

		accPref = PreferenceShUtil.getValue(activity,
				PreferenceShUtil.KEY_ACC, "");
		if (accPref.isEmpty()) {
			Intent intent = new Intent(HomeActivity.this,
					WellcomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);

		} else {
//			String strInfoUser = 
//			userEntity = PreferenceShUtil.loadJson(accPref);
//			appication.setUserEntity(userEntity);
		}
	
	}
	
	private void initPopupAcc(View view){
		View popupView = inflater.inflate(R.layout.detail_acc_layout, null);
		popupWindowAcc = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		popupWindowAcc.setBackgroundDrawable(new BitmapDrawable());
		popupWindowAcc.setOutsideTouchable(true);
		popupWindowAcc.showAsDropDown(view);

	}
	
	private void initPopupSetting(View view){
		View popupView = inflater.inflate(R.layout.setting_popup_layout, null);
		TextView tvSetting = (TextView)popupView.findViewById(R.id.tvSetting);
		
		tvSetting.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(activity, SettingActivity.class);
				startActivity(intent);
				popWindowSetting.dismiss();
			}
		});
		
		popWindowSetting = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
		popWindowSetting.setBackgroundDrawable(new BitmapDrawable());
		popWindowSetting.setOutsideTouchable(true);
		popWindowSetting.showAsDropDown(view);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.ivMenu:
			initPopupSetting(ivMenu);
			Toast.makeText(activity, "click", 1000).show();
			break;
		case R.id.ivAcc:
			initPopupAcc(ivAcc);
			break;

		default:
			break;
		}
	}
	
	private void initData(){
		arrTopic = new ArrayList<TopicEntity>();
		arrSubTopic = new ArrayList<SubTopicEntity>();
		arrGameType = new ArrayList<GameTypeEntity>();
		
		TiengAnhApi.topicCase3(activity, new IAjaxCallbackMMK() {

			@Override
			public <T> void handler(T t, int code) {
				if (code == COMPLETE) {
					arrTopic = (ArrayList<TopicEntity>) t;
					
					fillData();
				} else if (code == ERROR) {
					Toast.makeText(activity, (String) t, 2000).show();
					
					Intent intent = new Intent(HomeActivity.this, WellcomeActivity.class);
					startActivity(intent);
					HomeActivity.this.finish();
				}
			}
		});
	}
	
	private ArrayList<SubTopicEntity> getSubTopicByTopic(int pos, ArrayList<TopicEntity> topicEntities){
		ArrayList<SubTopicEntity> subTopicEntities = new ArrayList<SubTopicEntity>();
		if(topicEntities.size() > 0){
			JSONArray jsonArray = topicEntities.get(pos).getjObjSubTopic();
			
			Log.d(TAG, "jsonArray::" + jsonArray.toString());
			
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.optJSONObject(i);
				SubTopicEntity subTopicEntity = new SubTopicEntity(jsonObject);
				
				subTopicEntities.add(subTopicEntity);
			}
		}else{
			subTopicEntities = new ArrayList<SubTopicEntity>();
		}
		return subTopicEntities;
	}
	
	private void fillData(){
		adapter1 = new TopicAdapter(activity, arrTopic, 2);
		
		this.fancyCoverFlowTopic.setAdapter(adapter1);
		
//		fancyCoverFlowTopic.setSelection(0);
//		fancyCoverFlowGame.setSelection(0);

		fancyCoverFlowTopic.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				slugTopic = adapter1.getItem(arg2).getSlug();
				slugTopicName = adapter1.getItem(arg2).getName();
				adapter1.setPos(arg2);
				fillDataPopup(arg2);
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		
		
	}
	
	private void fillDataPopup(int pos){
		arrSubTopic = new ArrayList<SubTopicEntity>();
		arrSubTopic = getSubTopicByTopic(pos, arrTopic);
		
		if(arrSubTopic.size() > 0){
			adapter2 = new SubTopicAdapter(HomeActivity.this,
					arrSubTopic, 0);
			fancyCoverFlowSubTopic.setAdapter(adapter2);
			fancyCoverFlowSubTopic.setSelection(0);
			
			fancyCoverFlowSubTopic.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					
					slugSubTopic = adapter2.getItem(arg2).getSlug();
					slugSubTopicName = adapter2.getItem(arg2).getName();
					adapter2.setPos(arg2);
					
					fillDataGame(arg2);
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {

				}
			});
		}else{
			adapter2 = new SubTopicAdapter(HomeActivity.this,
					arrSubTopic, 0);
			fancyCoverFlowSubTopic.setAdapter(adapter2);
		}
	}
	
	private void fillDataGame(int pos){
		//Load listGame
		arrGameType = new ArrayList<GameTypeEntity>();
		JSONArray jsonArray = arrSubTopic.get(pos).getjArrGameType();
		
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jObjGame = jsonArray.optJSONObject(i);
			GameTypeEntity gameTypeEntity = new GameTypeEntity(jObjGame);
			arrGameType.add(gameTypeEntity);
		}
		fancyCoverFlowGame.setAlwaysDrawnWithCacheEnabled(true);
		adapter3 = new GameAdapter(HomeActivity.this, arrGameType , 0);
		this.fancyCoverFlowGame.setAdapter(adapter3);
		
		
		fancyCoverFlowGame.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				
				adapter3.setPos(arg2);

				slugGame = adapter3.getItem(arg2).getSlug();
				thumbGame = adapter3.getItem(arg2).getUrl();
				slugGameName = adapter3.getItem(arg2).getName();
//				pos = arg2;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
	}
	
	private void initIntent(Intent intent){
		intent.putExtra(Define.INTENT_SLUG_GAME, slugGame);
		intent.putExtra(Define.INTENT_SLUG_SUB_TOPIC, slugSubTopic);
		intent.putExtra(Define.INTENT_SLUG_TOPIC, slugTopic);
		intent.putExtra(Define.INTENT_THUMB_GAME, thumbGame);
		intent.putExtra(Define.INTENT_SLUG_GAME_NAME, slugGameName);
		intent.putExtra(Define.INTENT_SLUG_SUB_TOPIC_NAME, slugSubTopicName);
		intent.putExtra(Define.INTENT_SLUG_TOPIC_NAME, slugTopicName);
	}
	
	
	

}
